package tech.windanchaos.blog.controller;


import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tech.windanchaos.blog.entity.*;
import tech.windanchaos.blog.service.ArticleService;

import java.util.ArrayList;
import java.util.List;

/**
 * 管理员controller
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    ArticleService articleService;

    /**
     * 后台首页直接显示主页
     */
    @GetMapping({"", "index"})
    public String index(Model model) {
        blog(1, 10, model);
        //搜索分类数据
        model.addAttribute("categoryList", articleService.getAllCategory());

        return "admin/index";
    }


    @GetMapping("/blog")
    public String blog(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                       @RequestParam(name = "size", required = false, defaultValue = "10") int size,
                       Model model) {
        //防止传参过大强制纠正
        if (size > 20) size = 20;
        List<ArticleDes> articleDesList = articleService.getArticlesByPageAdmin((page - 1) * size, size);
        //自己维护pageinfo中的个字段的值，页面通过调取pageinfo的方法来行为
        PageInfo pageInfo = new PageInfo(articleDesList);
        pageInfo.setNextPage(page + 1);
        pageInfo.setPrePage(page - 1);
        //控制上一页和下一页显示与否的办法，是第一页不显示上一页，是最后一页，不显示下一页
        if (size > articleDesList.size()) {
            pageInfo.setIsLastPage(true);
        } else pageInfo.setIsLastPage(false);
        //取得的数据没有size那么长说明最后一页了。刚好最后一页是长度和size一样无法判定
        if (size > articleDesList.size()) {
            pageInfo.setIsLastPage(true);
        }
        if (pageInfo.getPrePage() <= 0) {
            pageInfo.setIsFirstPage(true);
        } else {
            pageInfo.setIsFirstPage(false);
        }
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("categories", articleService);
        //搜索分类数据
        model.addAttribute("categoryList", articleService.getAllCategory());
        //搜索
        SearchBody searchBody = new SearchBody();
        model.addAttribute("searchBody", searchBody);

        return "admin/index";
    }

    /**
     * 搜索
     *
     * @param model
     * @return
     */

    @PostMapping("/blog/search")
    public String searchBlog(Model model, SearchBody searchBody) {
        //执行查询并把结果放回model
        List<ArticleDes> articleDesList = articleService.searchBlogByCategoryIdAndTitle(searchBody);
        //自己维护pageinfo中的个字段的值，页面通过调取pageinfo的方法来行为
        PageInfo pageInfo = new PageInfo(articleDesList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("categories", articleService);
        //搜索分类数据
        model.addAttribute("categoryList", articleService.getAllCategory());

        return "admin/index";
    }

    /**
     * 分类管理：列表
     */

    @GetMapping("/category")
    public String category(Model model) {
        List<Category> categoryList = articleService.getAllCategory();
        model.addAttribute("categoryList", categoryList);
        return "admin/category";
    }

    /**
     * 分类管理：新增/编辑
     */
    @Transactional
    @GetMapping("/category/edit")
    public String addCategory(Model model,
                              @RequestParam(name = "id", required = false, defaultValue = "") Integer id) {
        Category category = new Category();
        if (null != id) {
            category = articleService.getCategoryByID(id);
            model.addAttribute("category", category);
        } else {
            model.addAttribute("category", category);
        }

        return "admin/category";
    }
    @Transactional
    @PostMapping("/category/edit")
    public String addCategory(Model model,
                              @RequestParam(name = "id", required = false, defaultValue = "") Integer id,
                              @RequestParam(name = "name", required = false, defaultValue = "") String name,
                              Category category) {
        if (null == articleService.getCategoryByName(category.getName()) && null == id) {
            articleService.addCategory(category.getName());
        } else {
            articleService.updateCategory(category);
        }
        return "redirect:/admin/category";
    }
    @Transactional
    @GetMapping("/category/del/{id}")
    public String delCategory(Model model,
                              @PathVariable Integer id) {
        if (articleService.getCategoryByID(id) != null) {
            articleService.delCategory(id);
        }
        return "admin/category";
    }

    /**
     * 标签管理
     */
    /**
     * 标签管理：列表
     */

    @GetMapping("/tags")
    public String tags(Model model) {
        List<Tag> tagsList = articleService.getAllTags();
        model.addAttribute("tagsList", tagsList);
        return "admin/tags";
    }

    /**
     * 标签管理：新增/编辑
     */
    @Transactional
    @GetMapping("/tags/edit")
    public String addTag(Model model,
                         @RequestParam(name = "id", required = false, defaultValue = "") Integer id) {
        Tag tag = new Tag();
        if (null != id) {
            tag = articleService.getTagByID(id);
            model.addAttribute("tags", tag);
        } else {
            model.addAttribute("tags", tag);
        }

        return "admin/tags";
    }
    @Transactional
    @PostMapping("/tags/edit")
    public String addTag(Model model,
                         @RequestParam(name = "id", required = false, defaultValue = "") Integer id,
                         @RequestParam(name = "name", required = false, defaultValue = "") String name,
                         Tag tag) {
        if (null == articleService.getTagByName(tag.getName()) && null == id) {
            articleService.addTag(tag.getName());
        } else {
            articleService.updateTag(tag);
        }
        return "redirect:/admin/tags";
    }
    @Transactional
    @GetMapping("/tags/del/{id}")
    public String delTag(Model model,
                         @PathVariable Integer id) {
        if (articleService.getTagByID(id) != null) {
            articleService.delTag(id);
        }
        return "admin/tags";
    }

    /**
     * 博客新增、修改
     */
    @Transactional
    @GetMapping("/blog/edit")
    public String edit(Model model,
                       @RequestParam(name = "id", required = false, defaultValue = "") Integer id) {
        //分类
        model.addAttribute("categoryList", articleService.getAllCategory());
        //标签
        model.addAttribute("tagsList", articleService.getAllTags());
        //编辑
        PubArticle blog;
        Article article;
        if (null != id && null != articleService.getArticleByID(id)){
            blog =new PubArticle();
            article=articleService.getArticleByID(id);
            blog.setArticle(article);
            List<Category> categories=articleService.getArticleCategoryById(id);
            List<Tag> tags=articleService.getArticleTagById(id);
            ACT act=new ACT();
            act.setCategoryIds(articleService.commitCategoryValues(categories));
            act.setTagIDs(articleService.commitTagsValues(tags));
            model.addAttribute("blog",blog);
            model.addAttribute("act",act);
        }else {
            blog =new PubArticle();
            article=new Article();
        }
        model.addAttribute("blog", blog);
        model.addAttribute("article", blog);
        return "admin/edit";
    }
    @Transactional
    @PostMapping("/blog/edit")
    public String pushBlog(Model model,
                       @RequestParam(name = "id", required = false,defaultValue = "") Integer id,
                           PubArticle blog,Article article,ACT act) {
        //分类
        String categoryIds=act.getCategoryIds();
        List<Integer> cIds=articleService.splitValues(categoryIds);

        //标签
        String tagIDs=act.getTagIDs();
        List<Integer> tIds=articleService.splitValues(tagIDs);
        blog.setArticle(article);

        //使用正文前200字符作为描述
        article.setDes(article.getContent().substring(0,200));;

        //编辑
        if (null!=id){
            articleService.updateArticle(article);
            articleService.categoryUpdate(id.intValue(),cIds);
            articleService.tagsUpdate(id.intValue(),tIds);
        }else {
            Integer articleId=articleService.insertArticle(article);
            articleService.categoryUpdate(articleId,cIds);
            articleService.tagsUpdate(articleId,tIds);
        }
        return index(model);
    }
    @Transactional
    @GetMapping("/blog/del/{id}")
    public String delBolg(Model model,@PathVariable (name = "id", required = true) Integer id){
        articleService.deleteArticle(id);
        return "redirect:/admin/index";
    }
}
